package com.lqq.sharding;

import com.google.common.collect.Range;
import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.api.algorithm.sharding.RangeShardingValue;
import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import io.shardingsphere.api.algorithm.sharding.standard.RangeShardingAlgorithm;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 每天一张表
 * = in 只需要实现 PreciseShardingAlgorithm
 * between and  需要实现 RangeShardingAlgorithm
 * @author liangqq
 */
public class EveryDayShardingAlgorithm implements PreciseShardingAlgorithm, RangeShardingAlgorithm {
    // <LocalDateTime>  泛型接收到的是Timestamp？

    @Override
    public String doSharding(Collection availableTargetNames, PreciseShardingValue shardingValue) {
        if(shardingValue.getValue() instanceof Timestamp){
            Timestamp timestamp = (Timestamp)shardingValue.getValue();
            String actualTableName = shardingValue.getLogicTableName() + formatDate(timestamp);
            return actualTableName;
        }
        throw new RuntimeException("日期为空，无法分表");
    }



    @Override
    public Collection<String> doSharding(Collection availableTargetNames, RangeShardingValue shardingValue) {

        Range range = shardingValue.getValueRange();

        Timestamp lowerEnd = (Timestamp)range.lowerEndpoint();
        Timestamp upperEnd = (Timestamp)range.upperEndpoint();
        //假设两个范围值都不为空, 计算所在的天数，这里忽略计算过程，直接返回 TODO 使用的是假数据
        List<String> tables = new ArrayList<>();
        tables.add(shardingValue.getLogicTableName() + formatDate(lowerEnd));
        tables.add(shardingValue.getLogicTableName() + formatDate(upperEnd));
        return tables;
    }


    /**
     * 返回 "yyyyMMdd"
     * @param timestamp
     * @return
     */
    private String formatDate(Timestamp timestamp ){
        Date d = new Date(timestamp.getTime());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        return simpleDateFormat.format(d);
    }

}
